package org.musmlib;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * WebStatus Servlet.<p>
 * 
 * Demonstration of <u>Master-Slave Pattern</u>:<p>
 * 
 * Three identical Servlet instances queried. Each is at a different network 
 * 	location. Equivalent results required from two out of the three 
 * 	instances.<p>
 */

public class Status extends HttpServlet
{
	private static final long serialVersionUID = 4639446484505193640L;

	
	@Override
	public void doGet( final HttpServletRequest req, 
		  			   final HttpServletResponse resp ) throws IOException 
	{
		resp.setContentType( "text/html" );
		resp.setStatus( HttpServletResponse.SC_ACCEPTED );
		resp.getOutputStream().println( "<HTML><BODY>Ready</BODY></HTML>" );		

    }//method
	
	
	@Override
	public void doPost( final HttpServletRequest req, 
		  			    final HttpServletResponse resp ) throws IOException 
    {		
		resp.setContentType( "text/html" );
		
		if( req.getParameter("website-status-url") != null && 
			req.getParameter("website-status-url").length() > 0 &&
			
			req.getParameter("content-expected") != null &&
			req.getParameter("content-expected").length() > 0 )
		{
			resp.setStatus( HttpServletResponse.SC_ACCEPTED );
			
			resp.getOutputStream().println( "<HTML><TITLE>" 
					
					+ req.getParameter("website-status-url") 
					
					+ "</TITLE><BODY>"
					
					+ websiteStatus( req.getParameter("website-status-url"), 
							
									 req.getParameter("content-expected")) 
					
					+ "</BODY></HTML>");
			
		}
		else
		{
			resp.setStatus( HttpServletResponse.SC_ACCEPTED );
			
			resp.getOutputStream().println( "<HTML><TITLE>" 
					
					+ req.getParameter("website-status-url") 
					
					+ "</TITLE><BODY></BODY></HTML>" );
			
		}//if
			
    }//method


	private String websiteStatus( final String url, 
			   		  		      final String contentExpected ) 
	{
		try
		{
			return websiteStatus( new URL(url), contentExpected );
		}
		catch( final MalformedURLException err )
		{
			return "error";
		
		}//try
		
	}//method
	
	
	private String websiteStatus( final URL url, 
								  final String contentExpected )
	{
		try
		{		
			BufferedReader in = new BufferedReader(
                    new InputStreamReader(url.openStream()));

			StringBuilder results = new StringBuilder();

			String line;
			while(( line = in.readLine()) != null )
				results.append( line + "\n" );
			in.close();
			
			if( results.toString().contains(contentExpected) )
			{
				return "online";
				
			}//if
			
		}
		catch( final IOException err )
		{
			return "error";
		
		}//try
		
		return "offline";
		
	}//method
	
	
}//class
